package org.jeecg.modules.demo.DingTalk;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.jeecg.modules.demo.util.DingTalkUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CreateInstance {

    @Autowired
    DingTalkUtil util;
    /**
     * 使用 Token 初始化账号Client
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalkworkflow_1_0.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkworkflow_1_0.Client(config);
    }

    /**
     * 根据流程编码发起流程实例
     * @param client 流程客户端
     * @param accessToken 访问令牌
     * @param userId 发起用户ID
     * @param processCode 流程编码
     * @param billno 金蝶单据编号
     * @param supplierAmountList 供应商金额列表
     * @return 审批单号
     * @throws Exception
     */
    public static String startProcessInstance(
            com.aliyun.dingtalkworkflow_1_0.Client client,
            String accessToken,
            String userId,
            String processCode, 
            String billno, 
            String purchaseOrgName,
            List<JSONObject> supplierAmountList) throws Exception {
        
        com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceHeaders startProcessInstanceHeaders = 
            new com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceHeaders();
        startProcessInstanceHeaders.xAcsDingtalkAccessToken = accessToken;
        
        // 金蝶汇总单号
        com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValues formComponentValue1 = 
            new com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValues()
                .setName("金蝶汇总单号")
                .setValue(billno);
        // 采购组织
        com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValues purchaseOrg =
            new com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValues()
                .setName("采购组织")
                .setValue(purchaseOrgName);
        
        // 构建表格组件数据
        List<String> tableRows = new ArrayList<>();
        for (JSONObject supplierAmount : supplierAmountList) {
            String supplierNumber = supplierAmount.getString("supplierName");
            String totalAmount = supplierAmount.getString("totalAmount");
            
            // 表格组件中的供应商
            com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValuesDetails tableDetails1 = 
                new com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValuesDetails()
                    .setName("供应商")
                    .setValue(supplierNumber != null ? supplierNumber : "");
                    
            // 表格组件中的付款金额
            com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValuesDetails tableDetails2 = 
                new com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValuesDetails()
                    .setName("付款金额")
                    .setValue(totalAmount != null ? totalAmount : "0");
            
            // 将表格行数据转换为JSON字符串
            JSONArray rowArray = new JSONArray();
            rowArray.add(tableDetails1);
            rowArray.add(tableDetails2);
            tableRows.add(rowArray.toString());
        }
        
        // 表格组件
        com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValues formComponentValue2 = 
            new com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValues()
                .setName("表格")
                .setValue(tableRows.toString());
        
        // 构建请求
        com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceRequest startProcessInstanceRequest = 
            new com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceRequest()
                .setOriginatorUserId(userId)
                .setProcessCode(processCode)
                .setDeptId(874559305L)
                .setFormComponentValues(java.util.Arrays.asList(
                        purchaseOrg,
                        formComponentValue1,
                        formComponentValue2
                ));
        
        // 发起流程实例
        com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceResponse startProcessInstanceResponse = 
            client.startProcessInstanceWithOptions(startProcessInstanceRequest, startProcessInstanceHeaders, new com.aliyun.teautil.models.RuntimeOptions());
        
        // 返回审批单号
        return startProcessInstanceResponse.getBody().getInstanceId();
    }
    
    /**
     * 根据流程编码直接发起流程实例
     * @param userId 发起用户ID
     * @param billno 金蝶单据编号
     * @param supplierAmountList 供应商金额列表
     * @return 审批单号
     * @throws Exception
     */
    public String createProcessInstanceByCode(String userId, String billno, String purchaseOrgName, List<JSONObject> supplierAmountList) throws Exception {
        // 获取访问令牌
        String accessToken = util.getAccessToken();
        
        // 初始化client
        com.aliyun.dingtalkworkflow_1_0.Client client = util.createClient();
        
        // 发起流程实例
        return startProcessInstance(
                client,
                accessToken,
                userId,
                "PROC-C759A8A6-7ED8-4DF5-B096-7989E4F13988",
                billno,
                purchaseOrgName,
                supplierAmountList
        );
    }
}